const HtmlWebpackPlugin = require("html-webpack-plugin");
const path = require("path");
//清除冗余文件
const { CleanWebpackPlugin: Clean } = require("clean-webpack-plugin");
// 自定义配置中，如果你不配置，webpack走自己的默认配置
//打包图片 file-loader url-loader
module.exports = {
  entry: "./code/index.js",
  output: {
    //路径--只给当前所有的处理模块指定一个公共的地址
    path: path.join(__dirname, "dist"),
    filename: "index.[hash:4].js",
    publicPath: "./",
  },
  devServer: {
    //静态服务的根路径，默认src
    contentBase: path.join(__dirname, "dist"),
    port: 8080,
    open: true,
  },
  //插件
  plugins: [
    //清除打包目录的冗余代码
    new Clean(),
    //处理html模板
    new HtmlWebpackPlugin({
      template: "./code/index.html",
      filename: path.join(__dirname, "./dist/index.html"),
      // publicPath:'./'
    }),
  ],
  //loader
  module: {
    rules: [
      //css
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      },
      //处理图片--样式里的图片file-loader和url-loader
      //匹配样式图片
      {
        test: /\.(png|jpg|svg|gif)$/,
        //url-loader 需要使用file-loader去生成真正的文件
        //limit 如果在设置的字节大小内，图片被转成base64，
        //超过后就变成真正的图片存储
        use: [
          {
            loader: "url-loader",
            options: {
              //以字节为单位
              limit: 1024, //byte--字节 1024 = 1kb
              //解决和html-loader报错问题
              esModule: false,
              //    publicPath:'./',
              outputPath: "imgs/",
              //[ext]是变量，ext:源文件的后缀
              name: "[path][name][ext]",
              //name:'[hash:6].[ext]'
            },
          },
        ],
      },
      //html里的img
      {
        test: /\.html$/,
        use: ["html-loader"],
      },
      //处理字体
      {
        test: /\.(eot|ttf|svg|woff|woff2)$/,
        use: {
          loader: "file-loader",
          options: {
            publicPath: "./",
            outputPath: "font/",
          },
        },
      },
      //处理es6
      {
        test: /\.(js|mjs|jsx)$/,
        //过滤掉下面的文件夹里的js，不进行编译
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: "babel-loader",
          //还需要一个配置项
          options: {
            presets: ["@babel/preset-env"],
          },
        },
      },
    ],
  },
};
